import { defineStore } from 'pinia'
import { apiDraftList, apiDraftView, apiDraftAddupdate } from '@renderer/api/bilibili'
import LZString from 'lz-string'
import chalk from 'chalk'
import { useUserStore } from '@renderer/stores/user'
import { v4 as uuidv4 } from 'uuid'
import dayjs from 'dayjs'

import type { ApiDraftAddupdateParams } from '@renderer/api/bilibili'
import type { AlbumTrackData, AlbumInfo, TrackInfo } from '@renderer/views/track/type'

interface State extends FavoriteCollection {}

export interface FavoriteInfo extends TrackInfo {}

export interface OwnplayInfo extends AlbumTrackData {
  id: string
}

interface FavoriteCollection {
  favorite: FavoriteInfo[]
  ownplay: OwnplayInfo[]
}

const blueBold = chalk.blueBright.bold
const { cookies } = window.api

export const useFavoriteStore = defineStore('favorite', {
  state: (): State => ({
    favorite: [],
    ownplay: []
  }),
  getters: {
    isFavorite: (state) => (cid: number) => {
      const item = state.favorite.find((f) => f.cid === cid)
      return !!item
    },
    favoriteTrack: (state) => {
      const { userAvatar, userName, userSign } = useUserStore()
      const info: AlbumInfo = {
        cover: userAvatar,
        title: '我喜欢的音乐',
        author: userName,
        pubdate: dayjs().unix(),
        description: userSign,
        songcount: state.favorite.length
      }
      const trackData: AlbumTrackData = { info, tracks: state.favorite }
      return trackData
    }
  },
  actions: {
    toggleFavorite(item: FavoriteInfo) {
      const index = this.favorite.findIndex((f) => f.cid === item.cid)
      if (index > -1) {
        this.favorite.splice(index, 1)
      } else {
        this.favorite.unshift(item)
      }

      this.updateNote()
    },
    async getFavorite() {
      const data = await getNoteContent()
      console.log(blueBold('笔记数据===>'), data)
      if (data) {
        Object.keys(data).forEach((key) => (this[key] = data[key]))
      }
    },
    removePlaylist(id: string) {
      const index = this.ownplay.findIndex((f) => f.id === id)
      if (index > -1) {
        this.ownplay.splice(index, 1)
      }

      this.updateNote()
    },
    async addPlaylist(data: AlbumTrackData) {
      const play: OwnplayInfo = {
        id: uuidv4(),
        ...data
      }
      this.ownplay = [...this.ownplay, play]
      this.updateNote()
    },
    updateNote() {
      editNoteContent({
        favorite: this.favorite,
        ownplay: this.ownplay
      })
    }
  }
})

const targetTitle = () => 'BiliMusic' + useUserStore().userMid

async function getNoteList(): Promise<any[]> {
  const { artlist }: any = await apiDraftList()
  if (artlist) {
    return artlist.drafts
  }
  return []
}

async function getTargetNoteAid(): Promise<number | null> {
  const list = await getNoteList()
  const target = list.find((f) => f.title === targetTitle())
  if (target) {
    return target.id
  }
  return null
}

async function getNoteContent(): Promise<FavoriteCollection | null> {
  const aid = await getTargetNoteAid()
  if (aid) {
    const { data, code } = await apiDraftView({ aid })
    if (code === 0) {
      const parseContent = JSON.parse(data.content)
      const insert = parseContent.ops[0].insert
      // 用户在官方编辑器中编辑保存，会导致末尾有 \n 换行符
      // 暂时不用，测试发现只在尾部加任何字符都不影响
      // insert = insert.replace(/\n/g, '')
      const parseData = JSON.parse(LZString.decompress(insert))
      return parseData
    }
  }
  return null
}

async function editNoteContent(targetContent: FavoriteCollection) {
  const content = LZString.compress(JSON.stringify(targetContent))
  const csrf = await cookies('https://www.bilibili.com').getValue('bili_jct')
  const params: ApiDraftAddupdateParams = {
    title: targetTitle(),
    content: JSON.stringify({ ops: [{ insert: content }] }),
    csrf
  }
  const aid = await getTargetNoteAid()
  if (aid) params.aid = aid
  const { code, data } = await apiDraftAddupdate(params)
  if (code === 0) {
    console.log(blueBold('存笔记成功===>'), data)
  }
}
